import sqlite3
import os
import shutil
source = r'C:\ZiSyncBackup\EDI-AL10\DuoKan'
database = source + r'\Bookshelf.db'
connection = sqlite3.connect(database)
#print(type(connection))  <class 'sqlite3.Connection'>
cursor = connection.cursor()
#print(type(c))  <class 'sqlite3.Cursor'>
sql = "select book_uri,book_name,author,file_size,book_uuid,book_revision,datetime(added_date/1000, 'unixepoch', 'localtime') from books where file_size > 0"
sql += " and book_state = 'NORMAL'"
cursor.execute(sql)
#print(result.rowcount)
#print(type(result))  <class 'sqlite3.Cursor'>
result = cursor.fetchall()
#print(type(result))  <class 'list'>
for book in result:
    print('book =', book)
    book_uri = book[0]
    book_name = book[1]
    author = book[2]
    file_size = book[3]
    book_uuid = book[4]
    book_revision = book[5]
    added_date = book[6]
    #print('book_uri =', book_uri)
    book_source = str.replace(book_uri, 'file:///storage/emulated/0/DuoKan', source)
    book_source = book_source.replace('/', '\\')
    #print('Source =', book_source)
    target = source + '\Books' + '\\' + added_date[0:4]
    if not os.path.exists(target):
        os.makedirs(target)
    book_target = target + '\\' + book_name + ' - ' + author + '.' + book_revision + '.epub'
    #print('Target =', book_target)
    if os.path.exists(book_source):
        if os.path.getsize(book_source) == file_size:
            if not os.path.exists(book_target):
                print('Copy ', book_source, '...')
                print('  To ', book_target, '...')
                shutil.copyfile(book_source, book_target)
cursor.close()
connection.close()
